package com.lab.base.common.tree;


import com.lab.user.model.Function;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

public class Tree {
    private List<Node> nodes = new ArrayList<Node>();
    private Node root = null;

    public Tree(List<Function> functions) {
        for (Function function : functions
                ) {
            Node node = new Node(function.getId(), function.getParentId(), function.getName(), function.getState(),
                    new NodeAttribute(function.getId(), null == function.getUrl() ? "" : function.getUrl()), function.getSortId());
            nodes.add(node);
            if (node.getId() == 0) {
                root = node;
            }
        }

    }

    public List<Node> build(){
        buildTree(root);
        List<Node> result = new ArrayList<Node>();
        result.add(root);
        return result;
    }

    /**
     * 构建菜单树
     * @param parent
     */
    private void buildTree(Node parent) {
        Node node = null;
        for (Iterator<Node> iterator =nodes.iterator();iterator.hasNext();){
            if(Objects.equals(node.getParentId(),parent.getId())){
                parent.getChildren().add(node);
                buildTree(node);
            }
        }
    }
}
